package cn.buyclss.backend.service.impl.shop;

import cn.buyclss.backend.entity.domain.User;
import cn.buyclss.backend.entity.domain.shop.Goods;
import cn.buyclss.backend.entity.domain.shop.GoodsCategory;
import cn.buyclss.backend.entity.domain.shop.GoodsCategoryExample;
import cn.buyclss.backend.entity.domain.shop.GoodsExample;
import cn.buyclss.backend.entity.domain.shop.GoodsSpecs;
import cn.buyclss.backend.entity.domain.shop.GoodsSpecsExample;
import cn.buyclss.backend.entity.po.shop.GoodsPO;
import cn.buyclss.backend.entity.po.shop.GoodsSpecsPO;
import cn.buyclss.backend.entity.po.shop.ShopPO;
import cn.buyclss.backend.entity.support.RespResult;
import cn.buyclss.backend.entity.vo.shop.GoodsIdVO;
import cn.buyclss.backend.entity.vo.shop.GoodsStatusUpdateVO;
import cn.buyclss.backend.entity.vo.shop.GoodsVO;
import cn.buyclss.backend.mapper.shop.GoodsCategoryMapper;
import cn.buyclss.backend.mapper.shop.GoodsMapper;
import cn.buyclss.backend.mapper.shop.GoodsSpecsMapper;
import cn.buyclss.backend.mapper.shop.ShopMapper;
import cn.buyclss.backend.service.shop.GoodsService;
import cn.buyclss.backend.util.RandomUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: Cecurio
 * @create: 2019-03-19 13:02
 **/
@Service
public class GoodsServiceImpl implements GoodsService {

    private Logger logger = LoggerFactory.getLogger(GoodsServiceImpl.class);

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;

    @Autowired
    private GoodsSpecsMapper goodsSpecsMapper;

    @Override
    public RespResult addOne(GoodsVO goodsVO) {
        RespResult res = RespResult.successInstance();

        Goods goods = new Goods();
        // 设置一些不需要前端传递的值，设置一些默认值
        goods.setGoodsStatus(1); // 下架状态
        goods.setAlias(RandomUtils.createUUID());
        goods.setStockNum(0);
        goods.setCreatedTime(new Date());
        goods.setUpdatedTime(new Date());

        // 1、获取商店编号
        Subject subject = SecurityUtils.getSubject();
        Object obj = subject.getPrincipal();
        Integer uid = 0;
        if (obj instanceof User) {
            User user = (User) obj;
            uid = user.getId();
        } else {
            return RespResult.failureInstance("系统异常，稍后重试！");
        }

        List<ShopPO> shops = shopMapper.selectUserShop(uid);
        if (shops.size() < 1) {
            return RespResult.failureInstance("您还没有商铺，无法添加！");
        }
        Integer shopId = shops.get(0).getId();

        // 设置shop_id
        goods.setShopId(shopId);

        // 2、设置前端传来的值
        goods.setName(goodsVO.getName());
        if (goodsVO.getDescription() != null) {
            goods.setDescription(goodsVO.getDescription());
        } else {
            goods.setDescription("暂无描述");
        }
        goods.setImgList(goodsVO.getImgList());
        goods.setPrice(0L);
        goods.setPromotionPrice(0L);
        // 校验种类传参是否合法
        GoodsCategoryExample example = new GoodsCategoryExample();
        GoodsCategoryExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(goodsVO.getGoodsCategoryId());
        List<GoodsCategory> categoryList = goodsCategoryMapper.selectByExample(example);
        if (categoryList == null || categoryList.size() == 0) {
            return RespResult.failureInstance("商品种类数据错误，没有这种种类!");
        }
        goods.setGoodsCategoryId(goodsVO.getGoodsCategoryId());
        goods.setCode(goodsVO.getCode());

        Integer insertId = goodsMapper.insertSelective(goods);
        logger.info("插入商户" + goods.getShopId() + " 的商品" + goods.getName() + "，返回的影响的行数：" + insertId);
        res.putValue("newGoodId", goods.getId());
        return res;
    }

    @Override
    public RespResult getMyGoods(Integer pageIndex, Integer pageSize) {
        RespResult res = RespResult.successInstance();

        Subject subject = SecurityUtils.getSubject();
        Object obj = subject.getPrincipal();
        Integer uid = 0;
        if (obj instanceof User) {
            User user = (User) obj;
            uid = user.getId();
        } else {
            return RespResult.failureInstance("系统异常，稍后重试！");
        }

        // startPage(第几页, 多少条数据)
        PageHelper.startPage(pageIndex, pageSize);
        List<GoodsPO> goodsPOS = goodsMapper.selectGoodsByUserId(uid);
        // 用PageInfo对结果进行包装
        PageInfo<GoodsPO> pageInfo = new PageInfo<GoodsPO>(goodsPOS);
        res.putValue("pages", pageInfo);

        return res;
    }

    @Override
    public RespResult updateGoodsStatusById(GoodsStatusUpdateVO goodsStatusUpdateVO) {
        // 检查规格表是否


        return null;
    }

    @Override
    public RespResult shelfGoodsById(GoodsIdVO goodsIdVO) {
        RespResult res = RespResult.successInstance();

        // 1、检查此种商品是否有规格。如果有规格，才可以上架!
        GoodsSpecsExample example = new GoodsSpecsExample();
        GoodsSpecsExample.Criteria cr = example.createCriteria();
        cr.andGoodsIdEqualTo(goodsIdVO.getGoodsId());
        List<GoodsSpecs> goodsSpecsList = goodsSpecsMapper.selectByExample(example);
        if (goodsSpecsList == null || goodsSpecsList.size() < 1) {
            return RespResult.failureInstance("该商品暂无对应的规格，无法上架!");
        }
        // 2、修改商品为上架状态
        Goods goods = new Goods();
        goods.setId(goodsIdVO.getGoodsId());
        goods.setGoodsStatus(2);
        int affectedRows = goodsMapper.updateByPrimaryKeySelective(goods);
        logger.info("修改商品ID: " + goodsIdVO.getGoodsId() + " , 返回的影响的行数是: " + affectedRows);

        return res;
    }

    @Override
    public RespResult getGoodsSpecsByGoodsId(Integer goodsId) throws InvocationTargetException, IllegalAccessException {
        RespResult res = RespResult.successInstance();

        // 通过goodsId换取goodsName
        GoodsExample goodsExample = new GoodsExample();
        GoodsExample.Criteria criteria = goodsExample.createCriteria();
        criteria.andIdEqualTo(goodsId);
        List<Goods> goodsList = goodsMapper.selectByExample(goodsExample);
        if (goodsList == null || goodsList.size() < 1) {
            return RespResult.failureInstance("该商品不存在");
        }

        GoodsPO goodsPO = new GoodsPO();
        BeanUtils.copyProperties(goodsPO, goodsList.get(0));

        GoodsSpecsExample example = new GoodsSpecsExample();
        GoodsSpecsExample.Criteria cr = example.createCriteria();
        cr.andGoodsIdEqualTo(goodsId);
        List<GoodsSpecs> goodsSpecsList = goodsSpecsMapper.selectByExample(example);
        List<GoodsSpecsPO> goodsSpecsPOList = new ArrayList<>();
        for (int i = 0; i < goodsSpecsList.size(); i++) {
            GoodsSpecsPO po = new GoodsSpecsPO();
            BeanUtils.copyProperties(po, goodsSpecsList.get(i));
            goodsSpecsPOList.add(po);
        }
        res.putValue("goods", goodsPO);
        res.putValue("goodsSpecs", goodsSpecsPOList);
        return res;
    }
}
